package com.gmail.yesguxun.tumblr.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import com.gmail.yesguxun.tumblr.TrAccount;
import com.gmail.yesguxun.tumblr.presenter.TrViewBigPhotoPresenter;
import com.gmail.yesguxun.tumblr.ui.R;
import com.gmail.yesguxun.util.DeviceInfo;
import com.gmail.yesguxun.util.LogFactory;
import com.gmail.yesguxun.util.LogX;

//only for 3.0 and above
//import android.app.ActionBar;
import android.app.Activity;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.os.Bundle;
//import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater; 
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


//Todo: customer title bar ...
//http://www.helloandroid.com/tutorials/how-create-custom-titlebar

public class ViewBigPhotoActivity extends Activity implements OnTouchListener{
	
	private ImageView mImageView = null;
	private TrViewBigPhotoPresenter mPresenter = null;
	
	private LogX mLog = LogFactory.getLogObject();
	
	private PointF mTouchStartPoint = new PointF();
	private PointF mTouchEndPoint = new PointF();
	private int mSlideDistanceMin = 40;
	
	boolean mCustomTitleSupported = false;
	TextView mCustomTitleLeft = null;
	TextView mCustomTitleRight = null;
	
	private static ContextWrapper mContext = null;
	
	public static ContextWrapper getContextWrapper()
	{
		return mContext;
	}
		
	private void setStatusInfo(String info1, String info2)
	{
		if(info1 != null)
		{ 
			//getActionBar().setTitle("Following Pics");
			this.mCustomTitleLeft.setText(info1);
		}
		
		if(info2 != null)
		{
			//getActionBar().setSubtitle("");
			this.mCustomTitleRight.setText(info2);
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		this.mLog.debug("tumblr", "onCreate " + this);
		
        TrAccount account = TrAccount.getTrAccount();
        if(!account.isAccountInfoValid())
        {
            account.setContext(getApplicationContext());
            account.load();     
        }
        
		DeviceInfo.setContext(this.getApplicationContext());
		
		this.mCustomTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.view_big_img);
		setupTitleBar();
		
		mContext = this;

		mImageView = (ImageView) findViewById(R.id.big_image);
		mImageView.setOnTouchListener(this);	

		mPresenter = TrViewBigPhotoPresenter.getInstance();
		mPresenter.bind(this);
		
		setStatusInfo("Follow Pics", "");
	}
	
	
	
	public void setupTitleBar()
	{
		if (this.mCustomTitleSupported) {
            getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
            this.mCustomTitleLeft = (TextView) findViewById(R.id.titleTvLeft);
            this.mCustomTitleRight = (TextView) findViewById(R.id.titleTvRight);
            
            this.mCustomTitleLeft.setText(getText(R.string.app_name).toString());
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu (Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.view_big_pic, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    Toast toast = null;
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.save_content:
            boolean saveResult = this.mPresenter.saveContent();
            int stringId = 0; 
            if(saveResult)
            {
                stringId = R.string.info_save_ok;
            }
            else
            {
                stringId = R.string.info_save_ng;
            }
            toast = Toast.makeText(this.getApplicationContext(), stringId, Toast.LENGTH_SHORT);
            toast.show();
            mLog.debug("save content");
            return true;
	    case R.id.refresh_content:
	        this.mPresenter.refreshContent();
	        return true;
	    case R.id.account_setting:
	    	this.mPresenter.settingConfig();
	        return true;
	    case R.id.like_content:
	        this.mPresenter.likeContent();
	        toast = Toast.makeText(this.getApplicationContext(), R.string.info_added_to_likes, Toast.LENGTH_SHORT);
	        toast.show();
	        mLog.debug("like content");
	        return true;
	    default:
	        mLog.debug("option default");
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	@Override
	protected void onStart() {
	      
		super.onStart();	
		
		this.mLog.debug("tumblr", "onStart " + this);
		
		mContext = this;	
		this.mPresenter.onActivityStart();
	}
	
	@Override
    protected void onPause() {
	    // TODO Auto-generated method stub
	    super.onPause();
	    
	    this.mPresenter.onActivityPause();
    }

	@Override
    protected void onResume() {
	    // TODO Auto-generated method stub
	    super.onResume();
	    
	    this.mPresenter.onActivityResume();
    }
	
	@Override
    protected void onStop() {
	    // TODO Auto-generated method stub
	    super.onResume();
	    
	    this.mPresenter.onActivityStop();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        //ImageView view = (ImageView) v;
        
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            mTouchStartPoint.set(event.getX(), event.getY());
            //mLog.debug("tumblr", "ACTION_DOWN");           
            break;
        case MotionEvent.ACTION_POINTER_DOWN:            
            //mLog.debug("tumblr", "ACTION_POINTER_DOWN");
            break;
        case MotionEvent.ACTION_UP:
            mTouchEndPoint.set(event.getX(), event.getY());
            checkSlideAction();
            break;
        case MotionEvent.ACTION_POINTER_UP:
            //mLog.debug("tumblr", "ACTION_POINTER_UP");
            break;
        case MotionEvent.ACTION_MOVE:
            break;
        default:
            break;
        }
        
        return true;
    }
    
    private void checkSlideAction()
    {
        float distanceX = this.mTouchStartPoint.x - this.mTouchEndPoint.x;
        mLog.debug("tumblr", "Move Distance: " + distanceX);
        if(distanceX > this.mSlideDistanceMin)
        {
            mLog.debug("tumblr", "<<-- slide to left direction");
            mPresenter.slideLeft();
        }
        else if(distanceX < (0 - this.mSlideDistanceMin))
        {
            mLog.debug("tumblr", "-->> slide to right direction");
            mPresenter.slideRight();
        }
    }
    
    public void setContentUri(String picUri)
    {
        String imagePath = picUri;
       
        this.mLog.debug("tumblr", "Set view of URL " + imagePath);
        
        try {
            if(imagePath != null)
            {
                Bitmap bm = BitmapFactory.decodeStream(new FileInputStream(imagePath));
                mImageView.setImageBitmap(bm);
            }
            else
            {
                //http://stackoverflow.com/questions/2859212/how-to-clear-an-imageview-in-android
                mImageView.setImageDrawable(null);
            }
        } catch (FileNotFoundException e) {
        	mLog.debug("tumblr", "setContentUri error: " + imagePath);
        }
        
    }
    
    public void setContentInfoOffset(int current, int total)
    {
    	this.setStatusInfo(null, "" + (current + 1) + "/" + total);
    }
    
    public void onFailedToSlideNext()
    {
    	Toast toast = Toast.makeText(this.getApplicationContext(), R.string.info_falied_to_next, Toast.LENGTH_SHORT);
    	toast.show();
    }


}
